
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Collections;
using System.Configuration;
using System.Diagnostics;
using System.Management.Instrumentation;
using System.Runtime.Remoting;

using Swaf;
using Swaf.Config;
using Swaf.BizRule;
using Swaf.Container;
using Swaf.Logging;

namespace Swaf.Instrumentation
{

	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	public class AppInstrumentation : IConfigPartner,IAppInstrumentation
	{
		protected IApplication m_app;
		protected IRuleMonitor m_ruleMonitor;
		protected IRuleMonitor m_perfMonRuleMonitor;
		protected IDictionary m_registeredCounters = new ThreadSafeHashtable();
		protected string m_categoryName="";
		protected string m_description="";

		public AppInstrumentation(IApplication app)
		{
			m_app = app;
			
		}
		public IPerformanceCounter getCounter(string counterName)
		{
			if (m_registeredCounters.Contains(counterName))
				return m_registeredCounters[counterName] as IPerformanceCounter;
			else
				return null;
		}
		public IPerformanceCounter registerCounterHandler(string name,string type)
		{
			IClassFactory factory = m_app.factories["PerformanceCounters"];
			IPerformanceCounter handler = (IPerformanceCounter) factory.createFromNickName(type,m_app,name);
			m_registeredCounters.Add(name,handler);
			return handler;
		}
		private void initializeCounters()
		{
			m_categoryName= m_app.resMgr.getMacro("ApplicationId");
			m_description = m_app.resMgr.getMacro("ApplicationDescription");
			CounterCreationDataCollection ccdc=new CounterCreationDataCollection();
			bool countersCreated=false;
			foreach(DictionaryEntry entry in m_registeredCounters)
			{
				IPerformanceCounter counter = entry.Value as IPerformanceCounter;
				counter.categoryName=m_categoryName;
				countersCreated=counter.createCounters(ccdc) || countersCreated;
			}
			if (countersCreated)
			{
				foreach(DictionaryEntry entry in m_registeredCounters)
				{
					IPerformanceCounter counter = entry.Value as IPerformanceCounter;
					m_app.Log.println(Application.NORMAL_STARTUP_LOG_LEVEL,"Created Performance Counter {0} for Application {1}", counter.name, counter.categoryName);
				}
				if (PerformanceCounterCategory.Exists(m_categoryName))
				{
					//Remove the old category.
					PerformanceCounterCategory.Delete(m_categoryName);
				}
				PerformanceCounterCategory.Create(m_categoryName, m_description, ccdc);
			}
			foreach(DictionaryEntry entry in m_registeredCounters)
			{
				IPerformanceCounter counter = entry.Value as IPerformanceCounter;
				counter.initCounters();
				m_app.Log.println(Application.NORMAL_STARTUP_LOG_LEVEL,"Initialized Performance Counter {0} for Application {1}", counter.name, counter.categoryName);
			}

		}
		public void registerForConfig(IConfigManager config)
		{
			config.registerHandler("...<PerformanceCounter>", new PerformanceCounterHandler(this));
		}

		public void checkConfigStatus()
		{
			registerCounterHandler("AverageRuleExecutionTime", "average");
			registerCounterHandler("CurrentNumExecutingRules","counter");
			registerCounterHandler("CurrentNumEnqueuedRules","counter");
			initializeCounters();
			m_perfMonRuleMonitor = new PerformanceCounterRuleMonitor(m_app.resMgr.getMacro("ApplicationId"), m_app.resMgr.getMacro("ApplicationDescription"));
			if(m_perfMonRuleMonitor != null)
				m_app.ruleMgr.addMonitor(m_perfMonRuleMonitor);
		}

		public class PerformanceCounterHandler : ConfigHandler
		{
			protected static string[] s_legalAttributes = new string[]{"name","type"};
			private AppInstrumentation m_mgr;
			public PerformanceCounterHandler(AppInstrumentation mgr) {m_mgr = mgr;}
			public override void  executeBefore(IConfigElement configInfo)
			{
				PerformanceCounterType defType;
				string errMsg = "PerformanceCounter nodes must have a valid name and counterType attribute.  Valid values for counterType are any valid entries in the PerformanceCounters class factory.";
				configInfo.checkIllegalAttributes(s_legalAttributes);
				string name=configInfo.getAttribute("name",string.Empty);
				if (name.Equals((string.Empty)))
					throw new ConfigurationException(errMsg);
				string counterType = configInfo.getAttribute("type", name);
				m_mgr.registerCounterHandler(name,counterType);
			}
		}


	
	}
}
